package com.alibaba.cirtus.ots.application.adapter.ability.utils;


import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.cz.base.tool.trace.TraceUtil;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import javax.xml.bind.DatatypeConverter;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 外部OpenApi http请求工具类
 */
@Component
public class OutOpenapiHttpUtils {

    private static final Log log = Log.getLogger(OutOpenapiHttpUtils.class);

//    @Value("${openapi.clientId}")
    private String clientId = "a4170568-7753-4faa-9705-687753efaac5";

//    @Value("${openapi.secret}")
    private String secret = "F367CFD5-C766-412E-A7CF-D5C766A12EAA";

    /**
     * 域名
     */
//    @Value("${openapi.url.prefix}")
    private String urlPrefix = "https://t-openapi-gateway.mengniu.cn/fulfillment-center";

    @Autowired
    private HttpUtils httpUtils;

    public Map<String, String> generateHttpHeader() {
        Map<String, String> headers = new HashMap<>();
        long time = new Date().getTime();
        MessageDigest md5;
        String sign = "";
        try {
            md5 = MessageDigest.getInstance("MD5");
            md5.update(buildKeyword(time).getBytes(StandardCharsets.UTF_8));
            byte[] digest = md5.digest();
            sign = DatatypeConverter.printHexBinary(digest).toUpperCase();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
        headers.put("clientID", clientId);
        headers.put("sign", sign);
        headers.put("t", String.valueOf(time));
        headers.put("Content-Type", "application/json");
        headers.put("Accept", "application/json");
        return headers;
    }

    private String buildKeyword(long time){
        StringBuffer keyword = new StringBuffer();
        keyword.append(clientId).append(secret).append(time);
        return keyword.toString();
    }

    public  <T> ResponseEntity<T> post(String url, Object requestBody, Class<T> responseType) {
        Map<String, String> headers = generateHttpHeader();
        //设置下traceID
        String traceId = TraceUtil.getTraceId();
        headers.put("x-trace-id",traceId);
        url = urlPrefix + url;
        log.info("OutOpenapiHttpUtils_post: url:{},  headers:{}, requestBody:{}", url, JSON.toJSONString(headers), JSON.toJSONString(requestBody));
        try{
            ResponseEntity<T> post = httpUtils.post(url, headers, requestBody, responseType);
            return post;
        }catch (Exception e){
            log.error("OutOpenapiHttpUtils_post error",e);
        }
        return null;

    }

    public  <T> ResponseEntity<T> post(String url, Map<String, String> headers, Object requestBody, Class<T> responseType) {

        return httpUtils.post(url, headers, requestBody, responseType);
    }

    public  <T> ResponseEntity<T> post(String url, HttpHeaders headers, Object requestBody, Class<T> responseType) {
        return  httpUtils.post(url, headers, requestBody, responseType);
    }

    public  <T> ResponseEntity<T> post(String url, HttpEntity<?> requestEntity, Class<T> responseType) {
        return  httpUtils.post(url, requestEntity, responseType);
    }
}
